package com.sghd.candy.net;

import com.sghd.candy.module.common.event.LogoutEvent;
import com.sghd.candy.module.player.manager.Player;
import com.sghd.candy.module.player.service.PlayerService;
import com.sghd.common.event.Event;
import com.sghd.common.event.EventBus;
import com.sghd.common.socket.session.Session;
import com.sghd.common.socket.session.SessionClose;
import com.sghd.common.socket.session.SessionOpen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author frank
 * @date 2018-10-31 16:56
 * @desc
 **/
@Component
public class SessionEvent implements SessionClose, SessionOpen {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private EventBus eventBus;
    @Autowired
    private PlayerService playerService;

    @Override
    public void sessionClosed(Session session, int cause) {
        Object identity = session.getIdentity();
        if (identity == null) {
            return;
        }
        Player player = playerService.load((Long) identity);
        switch (cause) {
            case Session.INTERRUPT:
                logger.debug("玩家[{}]连接中断,发出登出事件！", player.getId());
                break;
            case Session.KICK:
                logger.debug("玩家[{}]被踢下线,发出登出事件！", player.getId());
                break;
            case Session.TIMEOUT:
                logger.debug("玩家[{}]超时退出,发出登出事件！", player.getId());
                break;
        }
        Event<LogoutEvent> disconnectEvent = LogoutEvent.valueOf(player, cause, session);
        eventBus.post(disconnectEvent);
    }

    @Override
    public void sessionOpened(Session session) {
    }
}

